import { defineStore } from "pinia"
import { ref } from "vue"
import { getMatchesApi, getEventListApi } from "@/pages/xinhaozhi/apis/index"
import type * as Football from "@/pages/xinhaozhi/apis/type"

interface LeagueOption {
  value: string
  label: string
  fid: number
}

interface EventOption {
  value: string
  label: string
}

export const useLeagueStore = defineStore("league", () => {
  // State
  const leagueOptions = ref<LeagueOption[]>([])
  const selectedLeague = ref<LeagueOption | null>(null)
  const isLoadingLeagues = ref(false)
  const parsedLeagueInfo = ref<string>("")
  
  // 赛事名称相关状态
  const eventOptions = ref<EventOption[]>([])
  const selectedEvent = ref<string>("")
  const isLoadingEvents = ref(false)

  // Actions
  /** 根据时间范围获取比赛列表 */
  async function fetchLeaguesByDateRange(dateRange: { start: string; end: string }, eventName?: string) {
    console.log("根据时间范围检索比赛列表:", dateRange, "赛事名称:", eventName)
    isLoadingLeagues.value = true
    try {
      const requestData: Football.RequestData = {
        s_time: dateRange.start,
        e_time: dateRange.end,
        event_name: eventName || undefined
      }
      
      const response = await getMatchesApi(requestData)
      
      if (response.code === 0 && response.data) {
        const leagues: LeagueOption[] = response.data.map((match: Football.Matches) => ({
          value: match.fid?.toString() || '',
          label: `${match.event_name || '未知赛事'} ${match.matchtime ? new Date(match.matchtime).toLocaleDateString() : ''} ${match.homesxname || '主队'} vs ${match.awaysxname || '客队'} 比分 ${match.homescore}-${match.awayscore}`,
          fid: match.fid || 0
        })).filter(league => league.value && league.fid > 0)
        
        leagueOptions.value = leagues
        console.log("成功获取比赛列表:", leagues)
      } else {
        console.error("获取比赛列表失败:", response.message)
        leagueOptions.value = []
      }
    } catch (error) {
      console.error("Failed to fetch matches:", error)
      leagueOptions.value = []
    } finally {
      isLoadingLeagues.value = false
    }
  }

  /** 获取赛事列表 */
  async function fetchEventList() {
    console.log("获取赛事列表")
    isLoadingEvents.value = true
    try {
      const response = await getEventListApi()
      
      if (response.code === 0 && response.data) {
        const events: EventOption[] = response.data.map((event: Football.EventList) => ({
          value: event.event_name || '',
          label: event.event_name || '未知赛事'
        })).filter(event => event.value)
        
        eventOptions.value = events
        console.log("成功获取赛事列表:", events)
      } else {
        console.error("获取赛事列表失败:", response.message)
        eventOptions.value = []
      }
    } catch (error) {
      console.error("Failed to fetch event list:", error)
      eventOptions.value = []
    } finally {
      isLoadingEvents.value = false
    }
  }

  /** 选择比赛 */
  function selectLeague(leagueId: string) {
    const league = leagueOptions.value.find(l => l.value === leagueId)
    if (!league) {
      console.error("未找到选中的比赛")
      return null
    }

    selectedLeague.value = league
    parsedLeagueInfo.value = league.label
    console.log("当前选择的比赛:", league)
    
    return league
  }

  /** 重置所有数据 */
  function resetAllData() {
    leagueOptions.value = []
    selectedLeague.value = null
    parsedLeagueInfo.value = ""
    selectedEvent.value = ""
  }

  return {
    // 状态
    leagueOptions,
    selectedLeague,
    isLoadingLeagues,
    parsedLeagueInfo,
    eventOptions,
    selectedEvent,
    isLoadingEvents,
    
    // 方法
    fetchLeaguesByDateRange,
    fetchEventList,
    selectLeague,
    resetAllData
  }
})
